/**
 * Created by CJB on 2017-02-17 10:12:41.
 */


function initDate(timeId){
	//时间控件
	$("#"+ timeId).jeDate({
	    isinitVal:false,
	    festival: false,
	    skinCell:"jedateblue",
	    isTime:false,		   
	    format: 'YYYY-MM-DD'
	    
	});
}



function isPhoneValidator(){
	jQuery.validator.addMethod("isPhone", function(value,element) { 
		var mobile = /^1[34578]\d{9}$/; //手机号
		var tel = /^(\d{3,4}-)?\d{7,8}$/; //固话号
		return this.optional(element) || (mobile.test(value)) || (tel.test(value)); 
		
	}, "请正确填写号码"); 
}

//添加和修改页面单选框选择效果
function setDefaultStatusRadio(tableId, options){
    options = $.extend({
        callback:null
    },options || {});
    $("#"+tableId+" tr td div span.radio").click(function(){
        if(!$(this).hasClass('selected')){
            $("#"+tableId+" tr td span.radio").removeClass('selected');
            $(this).addClass('selected');
            if(options.callback && typeof (options.callback) == 'function')
                options.callback({target:this});
        }
    });
}

/**
 * 获取数据字典列表(适用于只有一级列表，不适用于树结构) lrs
 * @param selectId <select></select>的id  
 * @param dictionaryCode 数据字典编码
 * @param firstOption 默认第一项（例：--请选择--）
 * @param selectedValue <option value=""><option>中的value值,设置默认选中（用于编辑）
 */
function getDictionaryList(selectId, dictionaryCode, firstOption, selectedValue){
	if(firstOption){
		var htmlStr = "";
		htmlStr += "<option value=''>" + firstOption + "</option>";
		post(getPath() + "app/dictionary/tree/" + dictionaryCode,{},
            function(resultObject){
                if(resultObject.length > 0){
                    for(var i=1; i < resultObject.length; i++){
                        var item = resultObject[i];
                        htmlStr += "<option value='" + item.id + "'>" + item.name + "</option>";
                    }
                    $("#" + selectId).html(htmlStr);
                    //设置默认选中
                    if(selectedValue){
                    	$("#" + selectId + " option[value='" + selectedValue + "']").attr("selected",true);
                    }
                    else{
                    	$("#" + selectId + " option[value='" + firstOption + "']").attr("selected",true);
                    }
                }
            }
		);
	}else{
		post(getPath() + "app/dictionary/tree/" + dictionaryCode,{},
            function(resultObject){
                if(resultObject.length > 0){
                    var htmlStr = "";
                    for(var i=1; i < resultObject.length; i++){
                        var item = resultObject[i];
                        htmlStr += "<option value='" + item.id + "'>" + item.name + "</option>";
                    }
                    $("#" + selectId).html(htmlStr);
                    //设置默认选中
                    if(selectedValue){
                    	$("#" + selectId + " option[value='" + selectedValue + "']").attr("selected",true);
                    }
                }
            }
		);
	}
}

/**
 * 添加和编辑删除通讯录成功后的回调函数
 */
function phoneCallBack(){
	$("#rightDiv").load(getPath()+"base/userPhone/list/1/"+pageSize);
}
/**
 * 初始化移至分群
 */
function initMoveGroundDialog(){
	$("#moveGroundBtn").click(function(){
		var selectList = new Array();
        $("#baseUserPhoneTable tr td span.checkbox").each(function () {
            if ($(this).hasClass('selected'))
                selectList[selectList.length] = $(this).attr("id");
        });
        if(selectList.length == 0){
            createWindow('请选择要移动的人员。').dialog('open');
            return ;       			
		}else{
			var everyGroundTitleUl ="<ul id='moveGroundTitleUl' style='padding-top: 0px;'>	</ul>"
			$("#moveGroundDialog").html(everyGroundTitleUl);
			loadDiv.showLoading();
			post(getPath() + "mobile/ground/getAllCanMoveGroup",
					{},
					function(resultObject){
				var mobileGroundArr = resultObject.moveGroupList;
				console.log(mobileGroundArr.length);
				if(mobileGroundArr.length == 0){
					createWindow('您没有任何群。').dialog('open');
					loadDiv.hideLoading();
		            return ;  
				}else{
					var ids = selectList.join( "," );
					var everyGroundTitleLi = "";
					for(var i=0;i<mobileGroundArr.length;i++){
						everyGroundTitleLi += "<li id='li"+mobileGroundArr[i].id+"' onclick='moveGroundOnClick("+mobileGroundArr[i].id+")'><span id='"+mobileGroundArr[i].id+"'class='checkbox' style='float:left;margin-top:3px'>" +
							" </span><span id='#ground"+mobileGroundArr[i].id+"' class='groundName'>"+mobileGroundArr[i].name+"</span></li>";																				
					}
					$("#moveGroundTitleUl").html(everyGroundTitleLi);
					createMoveGroupWindow("moveGroundDialog","选择群",ids,{width:300}).dialog("open");
					loadDiv.hideLoading();
				}
			});
		}
	});
}
function moveGroundOnClick(spanId){
	var selectSpan = $("#"+spanId);
	if(!selectSpan.hasClass('selected')){
		selectSpan.addClass('selected');
	}else{
		selectSpan.removeClass('selected');
	}
}

/**
 * 创建移至分群弹出框
 */
function createMoveGroupWindow(id, label, userIds, options){
	options = $.extend({
        width: 400,
        height: 300
    },options || {});
	//初始化添加窗口
    var addWindow = $("#" + id);
    addWindow.dialog({
        autoOpen: false,
        width: options.width,
        height: options.height,
        resizable: false,
        title: label,
        modal: true,
        buttons: {
            "保存": function () {
                var groundList = new Array();
                $("#moveGroundDialog ul li span.checkbox").each(function () {
                    if ($(this).hasClass('selected'))
                    	groundList[groundList.length] = $(this).attr("id");
                });
                var groundIds = groundList.join( "," );
                if(groundIds.length ==0){
                	createWindow('请选择群').dialog('open');
		            return ;  
                }else{
                	loadDiv.showLoading();
    	        	post(getPath() + "mobile/userGround/add/"+userIds+"/"+groundIds,
    	                {},
    	                function(resultObject){    	                
    	                    //添加成功，弹出添加成功提示框，当用户点击确定后刷新页面
    	                	addWindow.dialog("close");
    	                	addWindow.empty();
    	                	loadDiv.hideLoading();
    	                    createWindow("移动成功",{url: getPath() + "mobile/ground/list"}).dialog("open");
    	                }
    	        	);
    	        
                }
                
            },
            "取消": function () {
                $(this).dialog("close");
                $(this).empty();
            }
        },
        close: function(){
        	$(".jBox-wrapper").remove();
        	$(this).empty();
        }
    });
    return addWindow;
}

/**
 * 清空群
 */
function emptyGroupClick(){
	$("#emptyGroundBtn").click(function(){
		var emptyGroundId = $("#groundId").val();
		var groundUserId = $("#groundUser"+emptyGroundId).val();
		var currentUserId = $("#currentUserId").val();
		if(emptyGroundId){
			if(groundUserId == currentUserId){
				createWindow('你确定要清空该群吗？',{
	            	cancleEnable:true,
	            	callBack:function(){
	            		post(getPath() + "mobile/userGround/empty/"+emptyGroundId,{},emptyGroupCallBack);
	            	}
				}).dialog('open');
			}else{
				createWindow('您无法清空群，请联系群主。',{width:220,height:160}).dialog('open');
			}
		}else{
			createWindow('请选中要清空的群').dialog('open');
		}		
	});
}

function emptyGroupCallBack(resultObject){
	createWindow("清空成功",{callBack:refreshGround}).dialog("open");
}
/***
 * 点击查询
 */
function setPhoneSearchBtnClick(url, options){
    options = $.extend({
        searchBtnId:'serachPhoneBtn',//查询按钮id
        formId:"searchForm",
        filterId:'isFilter'
    },options || {});
    //点击查询
    $("#" + options.searchBtnId).click(function(event){
        if(options.searchBtnId && url && options.formId){
            if(options.filterId)
                $('#' + options.filterId).val(1);
            $("#rightDiv").load(getPath() + url + $("#" + options.formId).serialize());
        }
        event.preventDefault();
    });
}


//分页插件
var jqp = null;
(function(){
	//初始化分页
	$(function () {
	    jqp = $.jqPaginator('#pagination', {
		    visiblePages: 10,
		    currentPage: pageNumber,
		    pageSize: pageSize,
		    totalCounts: totalCount,
		    onPageChange: function (num, type) {
		        if(num != pageNumber)
		        	$("#rightDiv").load(getPath() + "base/userPhone/list/"  + num +"/"+pageSize + ($("#isFilter").val() == 1 ? ("?" + $("#searchForm").serialize()) : ""));
		    }
	    });
//	    changeEvenColor("baseUserPhoneTable");
//	    selectAll("baseUserPhoneTable");//点击全选,判断是全选还是取消全选
//	    changTrCss("baseUserPhoneTable");//复选框选择改变，设置此行的样式，并判断当前情况是否为全选的情况
//	    changeTrCheckboxStatu("baseUserPhoneTable");//点击一行，改变这行的复选框勾选
//	    searchBtnClick("base/userPhone/list/1/"+pageSize+"?");//点击查询
//	    addBtnClick("base/userPhone/add");//打开添加窗口
//	    editBtnClick("baseUserPhoneTable","base/userPhone/edit/");
//	    deleteData("baseUserPhoneTable","base/userPhone/delete/","base/userPhone/list/1/"
//	    			+ pageSize + (isFilter ? ("?" + $("#searchForm").serialize()) : ""),135);//删除数据
	     
	    setGridListCheckBox("baseUserPhoneTable");//点击全选,判断是全选还是取消全选,判断当前情况是否为全选的情况
		setPhoneSearchBtnClick("base/userPhone/list/1/"+pageSize+"?");//搜索
		setAdvanceSearchBtnclick();//高级搜索
		setAddBtnClick("base/userPhone/add");//添加操作
		initMoveGroundDialog();//初始化移至分群
		deleteAllButton();//点击多选删除按钮
		emptyGroupClick();//清空群按钮
		changeGroupUserNameStyle();//群主名字变红
		//导出数据
		setExportBtnClick("base/userPhone/export",{
			tableId:"baseUserPhoneTable"
		});
	    //去除所有控件的虚线框
	    removeBlur();	   
	});
})();

function changeGroupUserNameStyle(){
	var groundId = $("#groundId").val();
	var groundUserId =$("#groundUserId").val();
	if(groundId){
		$("#nickName"+groundUserId).css("color","red");
	}
}
//单条通讯录点击发送短信事件
function sendMessage(userId){
	var userNickName = $("#nickName"+userId).text();
	var defaultPhone = $("#defaultPhone"+userId).text().trim();
	//console.log(userNickName+"!"+defaultPhone);
	if(!defaultPhone){
		createWindow('因无手机号，无法发送短信。',{width:220,height:160}).dialog('open');
	}else{
		$("#messageDialog").load(getPath()+"base/userPhone/messageView",
				{"userNickNames":userNickName,"phones":defaultPhone},
                function(resultObject){
                	
		});
		
	}
}
/*//多条通讯录点击发送短信事件
function sendMessages(){
	$("#messageBtn").click(function(){
		var selectList = new Array();
	    $("#baseUserPhoneTable tr td span.checkbox").each(function () {
	        if ($(this).hasClass('selected'))
	            selectList[selectList.length] = $(this).attr("id");
	    });
	    if(selectList.length == 0){
	        createWindow('请选择要发送短信的人员。').dialog('open');
	        return ;       			
		}else{
			
			var userNickName = $("#nickName"+userId).text();
			var defaultPhone = $("#defaultPhone"+userId).text().trim();
			console.log(userNickName+"!"+defaultPhone);
			if(!defaultPhone){
				createWindow('因无手机号，无法发送短信。',{width:220,height:160}).dialog('open');
			}else{
				$("#messageDialog").load(getPath()+"base/userPhone/messageView",
						{"userNickNames":userNickName,"phones":defaultPhone},
						function(resultObject){
							
						});
				
			}
		}
	});
}*/

/**
 *点击单个删除按钮执行的函数
 */
function deleteOneBtnClick(userId){
	var groundId = $("#groundId").val();
	var groundUserId =$("#groundUserId").val();
	var currentUserId = $("#currentUserId").val();
	if(groundId){
		if(groundUserId == currentUserId){
			if(userId == groundUserId ){
				createWindow('由于您是群主，无法将自己移除。',{width:220,height:160}).dialog('open');
			}else{
				gridDataDelete("mobile/userGround/delete/"+userId+"/"+groundId,{deleteSuccess:deleteOneCallBack});
			}	
		}else{
			createWindow('您无法删除该成员，请联系群主。',{width:220,height:160}).dialog('open');
		}
	}else{
		gridDataDelete("base/userPhone/delete/"+userId,{deleteSuccess:deleteCallBack});
	}
}

//将用户移除群的回调
function deleteOneCallBack(resultObject){
	loadDiv.hideLoading();
	createWindow("移出群成功。",{callBack:refreshGround}).dialog("open");
}
/**
 * 点击多选删除按钮
 */
function deleteAllButton(){
	$("#deleteBtn").click(function(){		
		var groundId = $("#groundId").val();
		var groundUserId =$("#groundUserId").val();
		var currentUserId = $("#currentUserId").val();
		if(groundId){
			if(groundUserId == currentUserId){
				 var selectList = new Array();
		            $("#baseUserPhoneTable tr td span.checkbox").each(function () {
		                if ($(this).hasClass('selected'))
		                    selectList[selectList.length] = $(this).attr("id");
		            });
		            if(selectList.length == 0){
		                createWindow('请选择要删除的数据').dialog('open');
		                return ;
		            }
		            for ( var i = 0; i < selectList.length; i++) {
						if(selectList[i] == groundUserId){
							/*selectList.remove(i);*/
							selectList.splice(i,1);
						}
					}
		            if(selectList.length == 0){
		            	createWindow('由于您是群主，无法将自己移除。',{width:220,height:160}).dialog('open');
		                return ;
		            }
			            createWindow('你确定要删除该数据？',{
			                cancleEnable:true,
			                callBack:function(){
			                	loadDiv.showLoading();
			                	var ids = selectList.join( "," );
			                    post(getPath() + "mobile/userGround/delete/"+ids+"/"+groundId,{}, successDelete);
			                }
			            }).dialog('open');
		            	
			}else{
				createWindow('您无法删除该成员，请联系群主。',{width:220,height:160}).dialog('open');
			}
		}else{
            var selectList = new Array();
            $("#baseUserPhoneTable tr td span.checkbox").each(function () {
                if ($(this).hasClass('selected'))
                    selectList[selectList.length] = $(this).attr("id");
            });
            if(selectList.length == 0){
                createWindow('请选择要删除的数据').dialog('open');
                return ;
            }
            createWindow('你确定要删除该数据？',{
                cancleEnable:true,
                callBack:function(){
                	loadDiv.showLoading();
                    var ids = selectList.join( "," );
                    post(getPath() + "base/userPhone/delete/" + ids,{}, deleteCallBack);
                }
            }).dialog('open');
        
		}
	});
}

/**
 * 删除通讯录时候的回调（非删除群成员）
 * @param resultObject
 */
function deleteCallBack(resultObject){
	loadDiv.hideLoading();
	createWindow(resultObject,{callBack:refreshGround}).dialog("open");
}
